import { defineStore } from 'pinia'
import { topCategory, subCategory } from '@/utils/constants'
import { findAllCategory, findAllGoods } from '@/apis/category'

export const categoryStore = defineStore('categoryStore', {
    state: () => {
        // 商品分类信息
        return {
            list: topCategory.map(item => {
                return {
                    name: item,
                }
            }),
            subList: subCategory.map(item => {
                return {
                    name: item,
                }
            }),
        }
    },
    actions: {
        // 请求商品分类信息
        async setList() {
            const result = await findAllCategory()
            const goods = await findAllGoods()
            // 给商品信息添加隐藏数据open
            result.forEach(item => {
                item.open = false
                item.goods = []
                goods.forEach(goodsItem => {
                    if (goodsItem.pid == item.id) {
                        item.goods.push(goodsItem)
                    }
                })
            })
            this.list = result
            this.subList = JSON.parse(JSON.stringify(this.list))
            // 循环成为左侧分类数据，移除多余数据
            this.subList.map(item => (item.sub = item.sub.slice(0, 2)))
        },
        // 显示和隐藏，更改open数据实现
        show(item) {
            const cate = this.list.find(
                categoryItem => categoryItem.id == item.id
            )
            cate.open = true
        },
        hide(item) {
            const cate = this.list.find(
                categoryItem => categoryItem.id == item.id
            )
            cate.open = false
        },
    },
    // persist: {
    //     // 开启数据持久化
    //     enabled: true,
    //     strategies: [
    //         {
    //             // 保存的名称
    //             key: 'categoryManage',
    //             storage: sessionStorage,
    //         },
    //     ],
    // },
})
